package com.ruicar.afs.cloud.apply.contract.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ruicar.afs.cloud.apply.business.service.ApplyMessageNotifyService;
import com.ruicar.afs.cloud.apply.business.service.ApplyRecordDetailsService;
import com.ruicar.afs.cloud.apply.business.service.TSysParamConfigService;
import com.ruicar.afs.cloud.apply.common.condition.DrawerCondition;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.feign.Apply2ChannelFeign;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.condition.*;
import com.ruicar.afs.cloud.apply.contract.enums.*;
import com.ruicar.afs.cloud.apply.contract.service.*;
import com.ruicar.afs.cloud.apply.contract.service.impl.ApplyContractInfoServiceImpl;
import com.ruicar.afs.cloud.apply.contract.service.impl.ContractMngServiceImpl;
import com.ruicar.afs.cloud.apply.contract.vo.*;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.approve.service.impl.PreApproveServiceImpl;
import com.ruicar.afs.cloud.apply.pre.approve.utils.ImageUploadUtil;
import com.ruicar.afs.cloud.apply.pre.loan.condition.OrderOprCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.bizcommon.business.condition.ApplyTotalCondition;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyFinancingItemsService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.security.vo.RoleVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.AffiliatedWayEnum;
import com.ruicar.afs.cloud.common.modules.apply.dto.ApplyIdCardDTO;
import com.ruicar.afs.cloud.common.modules.apply.dto.ApplyIdCardInfoDTO;
import com.ruicar.afs.cloud.common.rules.RuleHelper;
import com.ruicar.afs.cloud.common.rules.constants.RuleRunEnum;
import com.ruicar.afs.cloud.common.rules.dto.RuleRunResult;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.image.condition.OcrDiscernCondition;
import com.ruicar.afs.cloud.image.config.GwtFastdfsProperties;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.mapper.ComAttachmentManagementMapper;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.service.OcrDiscernService;
import com.ruicar.afs.cloud.image.store.enums.IsViewEnum;
import com.ruicar.afs.cloud.image.store.feign.ImageStoreApiFeign;
import com.ruicar.afs.cloud.parameter.commom.enums.OrderOprType;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 合同信息录入controller
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/contract")
public class ContractEntryController {

    //异常返回错误码
    private final String errorCode = "9999";
    private ApplyOrderInfoService applyOrderInfoService;
    private ApplyContractInfoService applyContractInfoService;
    private ApplyCarInvoiceService applyCarInvoiceService;
    private ApplyGpsInfoService applyGpsInfoService;
    private ApplyBankCardService applyBankCardService;
    private ApplyInsuranceInfoService applyInsuranceInfoService;
    private ApplyAffiliatedUnitService applyAffiliatedUnitService;
    private ApplyAddPriceItemsService applyAddPriceItemsService;
    private ApplyCustBaseInfoService applyCustBaseInfoService;
    private ApplyReturnRecordService applyReturnRecordService;
    private ApplyRecordDetailsService applyRecordDetailsService;
    private ApplyFinancingItemsService applyFinancingItemsService;
    private ApplyCustAddressDetailsService applyCustAddressDetailsService;
    private ApplyCustContactsService applyCustContactsService;
    private ApplyCarDetailsService applyCarDetailsService;
    private ApplyChannelInfoService applyChannelInfoService;
    private ApplyCustHistoryService applyCustHistoryService;
    private ApplyGpsOrderHistoryService applyGpsOrderHistoryService;
    private ApplyCostDetailsService applyCostDetailsService;
    private ApplyOprRecordService applyOprRecordService;
    private ApplyConfig config;
    private ContractMngService contractMngService;
    private Apply2ChannelFeign apply2ChannelFeign;
    private GpsProductInfoService gpsProductInfoService;
    private final ApplyContractInfoServiceImpl applyContractInfoServiceImpl;
    private LoanGpsRuleInfoService loanGpsRuleInfoService;
    private ComAttachmentManagementMapper comAttachmentManagementMapper;
    private final ContractMngServiceImpl contractMngServiceImpl;
    private ImageStoreApiFeign imageStoreApiFeign;
    private final PreApproveService preApproveService;
    private final ComAttachmentFileService comAttachmentFileService;
    private final ComAttachmentManagementMapper managementMapper;
    private final ImageUploadUtil imageUploadUtil;
    private final PreApproveServiceImpl preApproveServiceImpl;
    private final GwtFastdfsProperties fastdfsProperties;
    private final ApplyMessageNotifyService applyMessageNotifyService;
    private final OcrDiscernService ocrDiscernService;
    private final TSysParamConfigService tSysParamConfigService;

    @PostMapping("/entry/info")
    @ApiOperation(value = "获取合同基本信息")
    public IResponse contractEntryInfo(@RequestParam("applyNo") String applyNo) {
        ContractEntryCollectVO vo = new ContractEntryCollectVO();
        //订单表信息
        ApplyOrderInfo orderInfo = applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda()
                .eq(ApplyOrderInfo::getApplyNo, applyNo));
        //合作商信息
        ApplyChannelInfo applyChannelInfo = applyChannelInfoService.getOne(Wrappers.<ApplyChannelInfo>query().lambda().eq(ApplyChannelInfo::getApplyNo, applyNo));
        orderInfo.setChannelName(applyChannelInfo.getChannelName());
        //合同信息
        ApplyContractInfo contractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda().eq(ApplyContractInfo::getApplyNo, applyNo));
        //最低开票金额
        BigDecimal money = contractMngService.getMinInvoiceAmt(applyNo);
        //发票信息
        ApplyCarInvoice carInvoice = applyCarInvoiceService.getOne(Wrappers.<ApplyCarInvoice>query().lambda().eq(ApplyCarInvoice::getApplyNo, applyNo));
        //GPS信息
        ApplyGpsInfo gpsInfo = applyGpsInfoService.getOne(Wrappers.<ApplyGpsInfo>query().lambda().eq(ApplyGpsInfo::getApplyNo, applyNo));
        //银行信息
        ApplyBankCard bankCard = applyBankCardService.getOne(Wrappers.<ApplyBankCard>query().lambda().eq(ApplyBankCard::getApplyNo, applyNo));
        //保险信息
        List<ApplyInsuranceInfo> insuranceInfos = applyInsuranceInfoService.list(Wrappers.<ApplyInsuranceInfo>query().lambda().eq(ApplyInsuranceInfo::getApplyNo, applyNo).orderByAsc(ApplyInsuranceInfo::getInsuranceType));
        //挂靠信息
        ApplyAffiliatedUnit affiliatedUnit = applyAffiliatedUnitService.getOne(Wrappers.<ApplyAffiliatedUnit>query().lambda().eq(ApplyAffiliatedUnit::getApplyNo, applyNo));
        if(orderInfo.getAffiliatedWay().equals(AffiliatedWayEnum.PERSONAL_AFFILIATED.getCode())){
            if(affiliatedUnit.getModifyFlag()==null){
                affiliatedUnit.setSocUniCrtCode(null);
            }
        }
        //增融成交价信息
        List<ApplyAddPriceItems> addPriceItems = applyAddPriceItemsService.list(Wrappers.<ApplyAddPriceItems>query().lambda().eq(ApplyAddPriceItems::getApplyNo, applyNo));
        //客户信息主表
        List<ApplyCustBaseInfo> custBaseInfoList = new ArrayList();
        //客户信息历史表
        List<ApplyCustHistory> custHistoryList = applyCustHistoryService.list(Wrappers.<ApplyCustHistory>query().lambda().eq(ApplyCustHistory::getApplyNo, applyNo).notIn(ApplyCustHistory::getCustRole, ApplyConstants.GUARANTOR).orderByAsc(ApplyCustHistory::getCustRole));
        if (custHistoryList.size() == 0) {
            List<ApplyCustBaseInfo> custBaseInfos = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getApplyNo, applyNo).notIn(ApplyCustBaseInfo::getCustRole, ApplyConstants.GUARANTOR).orderByAsc(ApplyCustBaseInfo::getCustRole));
            custBaseInfos.forEach(en -> {
                ApplyCustHistory applyCustHistory = new ApplyCustHistory();
                BeanUtils.copyProperties(en, applyCustHistory);
                custHistoryList.add(applyCustHistory);
            });
        }
        //30天内过期的身份证要设置表格底色
        custHistoryList.forEach(en -> {
            if (en.getIsLongTerm()) {
                en.setIsExpire(false);
                ApplyCustBaseInfo applyCustBaseInfo = new ApplyCustBaseInfo();
                BeanUtils.copyProperties(en, applyCustBaseInfo);
                custBaseInfoList.add(applyCustBaseInfo);
            } else {
                int day = (int) ((en.getCertEndDate().getTime() - (Calendar.getInstance().getTime().getTime())) / (1000 * 3600 * 24));
                if (day <= 30) {
                    en.setIsExpire(true);
                }
                ApplyCustBaseInfo applyCustBaseInfo = new ApplyCustBaseInfo();
                BeanUtils.copyProperties(en, applyCustBaseInfo);
                custBaseInfoList.add(applyCustBaseInfo);
            }
        });
        //特殊业务申请信息
        List<ApplyOprRecord> specialBusiness = applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda().eq(ApplyOprRecord::getApplyNo, applyNo).eq(ApplyOprRecord::getApplyType, OrderOprType.TRANSFER));
        //流程主表信息
        List<ApplyReturnRecord> returnRecords = applyReturnRecordService.list(Wrappers.<ApplyReturnRecord>query().lambda().eq(ApplyReturnRecord::getContractNo, contractInfo.getContractNo() == null ? "" : contractInfo.getContractNo()).orderByDesc(ApplyReturnRecord::getCreateTime));
        if (returnRecords.size() > 0) {
            for (ApplyReturnRecord returnRecord : returnRecords) {
                ComAttachmentManagement comAttachmentManagement = this.comAttachmentManagementMapper.selectById(returnRecord.getReturnType());
                returnRecord.setReturnType(comAttachmentManagement.getAttachmentName());
                returnRecord.setUniqueCode(comAttachmentManagement.getUniqueCode());
                List<ComAttachmentManagement> comAttachmentManagements = this.comAttachmentManagementMapper.selectList(Wrappers.<ComAttachmentManagement>query().lambda().eq(ComAttachmentManagement::getParentId, comAttachmentManagement.getId().toString()));
                if (comAttachmentManagements.size() > 0) {
                    List<ComAttachmentFile> comAttachmentFile = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getAttachmentCode, comAttachmentManagements.get(0).getId().toString()).eq(ComAttachmentFile::getBusiNo, contractInfo.getContractNo()).eq(ComAttachmentFile::getHistoryVersion,"0"));
                    if (comAttachmentFile.size() > 0) {
                        returnRecord.setIsStandard(comAttachmentFile.get(0).getFileStatus());
                    }
                } else {
                    List<ComAttachmentFile> comAttachmentFile = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getAttachmentCode, comAttachmentManagement.getId().toString()).eq(ComAttachmentFile::getBusiNo, contractInfo.getContractNo()).eq(ComAttachmentFile::getHistoryVersion,"0"));
                    if (comAttachmentFile.size() > 0) {
                        returnRecord.setIsStandard(comAttachmentFile.get(0).getFileStatus());
                    }
                }
            }
        }
        //操作明细表
        List<WorkflowRecordDetails> recordDetails = applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda().eq(WorkflowRecordDetails::getBusinessNo, contractInfo.getContractNo() == null ? "" : contractInfo.getContractNo()).eq(WorkflowRecordDetails::getBusinessType, ApplyConstants.LOAN_APPROVAL));
        //附加贷信息
        List<FinFinancingItems> financingItems = applyFinancingItemsService.list(Wrappers.<FinFinancingItems>query().lambda().eq(FinFinancingItems::getApplyNo, applyNo).eq(FinFinancingItems::getIsView, true));
        //主借人信息
        ApplyCustBaseInfo applyCustBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getApplyNo, applyNo).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER));
        //主借人户籍地址
        ApplyCustAddressDetails custAddressDetails = applyCustAddressDetailsService.getOne(Wrappers.<ApplyCustAddressDetails>query().lambda().eq(ApplyCustAddressDetails::getApplyNo, applyNo).eq(ApplyCustAddressDetails::getAddressType, AddressTypeEnum.House.getCode()).eq(ApplyCustAddressDetails::getCustId, applyCustBaseInfo.getId()).eq(ApplyCustAddressDetails::getIsMain, IsMainEnum.isMain.getCode()));
        //车辆信息
        ApplyCarDetails carDetails = applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda().eq(ApplyCarDetails::getApplyNo, applyNo));
        //融资费用信息
        List<FinCostDetails> costDetails = applyCostDetailsService.list(Wrappers.<FinCostDetails>query().lambda().eq(FinCostDetails::getApplyNo, applyNo).eq(FinCostDetails::getCostType, ApplyConstants.COST_TYPE_CAR_LOAN));
        List<FinCostDetails> costDetailsList = applyCostDetailsService.list(Wrappers.<FinCostDetails>query().lambda().eq(FinCostDetails::getApplyNo, applyNo));
        BigDecimal loanMoneyAll=BigDecimal.ZERO;
        for(FinCostDetails finCostDetails:costDetailsList){
            loanMoneyAll=loanMoneyAll.add(finCostDetails.getLoanAmt()==null?BigDecimal.ZERO:finCostDetails.getLoanAmt());
        }
        //1.处理一下金额字段，将financingItems的金额字段置空再给页面
        financingItems.forEach(en -> {
            en.setFinanceItemAmt(null);
        });
        //2.如果addPriceItems有值，把addPriceItems里面对应的金额给financingItems
        financingItems.forEach(en -> {
            addPriceItems.forEach(e -> {
                if (en.getFinanceItemCode().equals(e.getFinanceItemCode())) {
                    en.setFinanceItemAmt(e.getAddFinanceAmt());
                }
            });
        });
        if (costDetails.size() > 0 && gpsInfo != null) {
            if (gpsInfo.getGpsSupplier() != null && !("").equals(gpsInfo.getGpsSupplier())) {
                GpsProductInfo gpsProductInfo = gpsProductInfoService.getOne(Wrappers.<GpsProductInfo>query().lambda()
                        .lt(GpsProductInfo::getDownTerm, costDetails.get(0).getLoanTerm())
                        .ge(GpsProductInfo::getUpTerm, costDetails.get(0).getLoanTerm())
                        .eq(GpsProductInfo::getGpsType, gpsInfo.getGpsType())
                        .eq(GpsProductInfo::getGpsFirm, gpsInfo.getGpsSupplier()));
                if(gpsProductInfo!=null){
                    vo.setGpsFullName(gpsProductInfo.getGpsFullName());
                }
            }
        }
        String isGreatWall = ApplyConstants.UN_GREAT_WALL;
        if (carDetails.getBrandName().indexOf(ApplyConstants.IS_GREAT_WALL) >= 0) {
            isGreatWall = ApplyConstants.GREAT_WALL;
        }
        BigDecimal loanAmt = BigDecimal.ZERO;
        for (FinCostDetails applyCostDetails : costDetails) {
            loanAmt = loanAmt.add(applyCostDetails.getLoanAmt());
        }
        String isInternet;
        if (carDetails.getIsInternet() == null || ("").equals(carDetails.getIsInternet()) || carDetails.getIsInternet().equals(ApplyConstants.UN_INTERNET)) {
            isInternet = ApplyConstants.IS_NOT_INTERNET;
        } else {
            isInternet = ApplyConstants.IS_INTERNET;
        }
        JSONObject runParams = new JSONObject();
        //是否长城品牌
        runParams.put("isGreatWall", isGreatWall);
        //业务类型
        runParams.put("businessType", orderInfo.getBusinessType());
        //车辆类型
        runParams.put("carType", orderInfo.getCarType());
        //车辆属性
        runParams.put("carNature", orderInfo.getCarNature());
        //是否车联网
        runParams.put("isOnline", isInternet);
        //贷款总额
        runParams.put("loanAmount", String.valueOf(loanAmt));
        //挂靠方式
        runParams.put("affiliatedWay", orderInfo.getAffiliatedWay());
        List<LoanGpsRuleInfo> rules = loanGpsRuleInfoService.list();
        List<String> ruleNoList = rules.stream().map(s -> String.valueOf(s.getId())).collect(Collectors.toList());
        RuleRunResult ruleRunResult = RuleHelper.runRule(runParams, ruleNoList, true, RuleRunEnum.SERIAL);
        if (ruleRunResult.getResults().size() > 0) {
            LoanGpsRuleInfo loanGpsRuleInfo = loanGpsRuleInfoService.getById(ruleRunResult.getResults().get(0).getRuleNo());
            if (loanGpsRuleInfo != null) {
                vo.setGpsType(loanGpsRuleInfo.getInstallType());
            }
        }
        if (orderInfo == null) {
            return IResponse.fail("订单信息为空");
        } else {
            orderInfo.setViewContractStatus(contractInfo.getContractStatus());
            orderInfo.setFirstCommitTime(contractInfo.getLendingFirstDate());
            orderInfo.setStartTime(contractInfo.getStartDate());
            orderInfo.setMoney(loanMoneyAll);
            orderInfo.setTerm(costDetails.get(0).getLoanTerm());
            vo.setOrderInfo(orderInfo);
        }
        if (carDetails == null) {
            return IResponse.fail("车辆信息为空");
        } else {
            vo.setCarDetails(carDetails);
        }
        if (custBaseInfoList == null) {
            return IResponse.fail("客户基本信息为空");
        } else {
            vo.setCustBaseInfos(custBaseInfoList);
        }
        vo.setCarInvoice(carInvoice != null ? carInvoice : new ApplyCarInvoice());
        vo.setGpsInfo(gpsInfo != null ? gpsInfo : new ApplyGpsInfo());
        vo.setContractInfo(contractInfo != null ? contractInfo : new ApplyContractInfo());
        vo.setBankCard(bankCard != null ? bankCard : new ApplyBankCard());
        vo.setAffiliatedUnit(affiliatedUnit != null ? affiliatedUnit : new ApplyAffiliatedUnit());
        vo.setCostDetails(costDetails);
        vo.setApplyOprRecords(specialBusiness);
        vo.setReturnRecords(returnRecords);
        vo.setRecordDetails(recordDetails);
        vo.setInvoiceAmt(money);
        vo.setFinancingItems(financingItems);
        vo.setAddPriceItems(addPriceItems);
        vo.setCustAddressDetails(custAddressDetails);
        vo.setInsuranceInfos(insuranceInfos);
        return new IResponse<ContractEntryCollectVO>().setData(vo);
    }

    @PostMapping("/account/person")
    @ApiOperation(value = "查询主共借人信息")
    public IResponse getAccountPerson(@RequestParam("applyNo") String applyNo) {
        List<ApplyCustBaseInfo> list = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, applyNo)
                .notIn(ApplyCustBaseInfo::getCustRole, ApplyConstants.GUARANTOR));
        return new IResponse().setData(list);
    }

    @PostMapping("/getLendingMode")
    @ApiOperation(value = "查询放款模式")
    public IResponse getLendingMode(@RequestParam("applyNo") String applyNo) {
        // TODO yusijun 从渠道获取有哪些放款模式
        return new IResponse().setData(Lists.newArrayList());
    }

    @Transactional
    @PostMapping("/save")
    @ApiOperation(value = "保存合同录入信息")
    public IResponse save(@RequestBody ContractEntryCollectVO vo) {
//        String contractNo = "";
        ApplyContractInfo contractInfo = vo.getContractInfo();
        if (vo.getContractInfo() != null) {
            vo.getCustBaseInfos().forEach(en -> {
                if (en.getCustRole().equals(ApplyConstants.PRINCIPAL_BORROWER)) {
                    contractInfo.setCustName(en.getCustName());
                }
            });
            JSONArray roleArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("roles");
            if(roleArray!=null){
                List<RoleVo> roleList = roleArray.toJavaList(RoleVo.class);
                for(RoleVo roleVo:roleList){
                    if(roleVo.getRoleCode().equals(ApplyConstants.ROLE_XCPAYMENT) || roleVo.getRoleCode().equals(ApplyConstants.ROLE_PAYMENT)){
                        contractInfo.setLoanReporter(SecurityUtils.getUsername());
                    }
                }
            }
            vo.getBankCard().setContractNo(contractInfo.getContractNo());
        }
        // 合同信息
        ApplyContractInfo applyContractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda().eq(ApplyContractInfo::getApplyNo, vo.getApplyNo()));

        // 车辆信息
        ApplyCarDetails carDetails = applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda().eq(ApplyCarDetails::getApplyNo, vo.getApplyNo()));
        if (carDetails == null) {
            vo.getCarDetails().setContractNo(contractInfo.getContractNo());
            applyCarDetailsService.save(vo.getCarDetails());
        } else {
            if(vo.getCarDetails().getEngineNo()!=null){
                if (!vo.getCarDetails().getEngineNo().equals(carDetails.getEngineNo())) {
                    contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                }
            }
            if(vo.getCarDetails().getCarVin()!=null){
                if (!vo.getCarDetails().getCarVin().equals(carDetails.getCarVin())) {
                    contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                }
            }
            if(vo.getCarDetails().getFullModelNum()!=null){
                if (!vo.getCarDetails().getFullModelNum().equals(carDetails.getFullModelNum())) {
                    contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                }
            }
            BeanUtils.copyProperties(vo.getCarDetails(), carDetails);
            carDetails.setContractNo(contractInfo.getContractNo());
            applyCarDetailsService.updateById(carDetails);
        }
        // 发票信息
        List<ApplyCarInvoice> applyCarInvoiceList = applyCarInvoiceService.list(Wrappers.<ApplyCarInvoice>query().lambda().eq(ApplyCarInvoice::getApplyNo, vo.getApplyNo()).orderByDesc(ApplyCarInvoice::getCreateTime));
        if (applyCarInvoiceList!=null && applyCarInvoiceList.size() > 0) {
            ApplyCarInvoice applyCarInvoice =  applyCarInvoiceList.get(0);
            Long id = applyCarInvoice.getId();
            if (vo.getOrderInfo().getBusinessType().equals(ApplyConstants.BUSINESS_TYPE_OLD_CAR)) {
                if (vo.getCarInvoice().getInvoiceNature() != null && !vo.getCarInvoice().getInvoiceNature().equals(applyCarInvoice.getInvoiceNature() == null ? "" : applyCarInvoice.getInvoiceNature())) {
                    contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                } else if (vo.getCarInvoice().getInvoiceUnit() != null && !vo.getCarInvoice().getInvoiceUnit().equals(applyCarInvoice.getInvoiceUnit() == null ? "" : applyCarInvoice.getInvoiceUnit())) {
                    contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                } else if (vo.getCarInvoice().getSaleName() != null && !vo.getCarInvoice().getSaleName().equals(applyCarInvoice.getSaleName() == null ? "" : applyCarInvoice.getSaleName())) {
                    contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                }
            } else {
                if (vo.getCarInvoice().getInvoiceUnit() != null && !vo.getCarInvoice().getInvoiceUnit().equals(applyCarInvoice.getInvoiceUnit() == null ? "" : applyCarInvoice.getInvoiceUnit())) {
                    contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                }
            }
            BeanUtils.copyProperties(vo.getCarInvoice(), applyCarInvoice);
            if(ObjectUtil.isNull(applyCarInvoice.getId())){
                applyCarInvoice.setId(id);
            }
            applyCarInvoiceService.updateById(applyCarInvoice);
        }else{
            ApplyCarInvoice applyCarInvoice = new ApplyCarInvoice();
            BeanUtils.copyProperties(vo.getCarInvoice(), applyCarInvoice);
            applyCarInvoice.setId(null);
            applyCarInvoice.setApplyNo(vo.getApplyNo());
            applyCarInvoice.setCarId(carDetails.getId().toString());
            applyCarInvoice.setCarVin(carDetails.getCarVin());
            applyCarInvoiceService.save(applyCarInvoice);
        }
        // 客户历史信息
        vo.getCustBaseInfos().forEach(en -> {
            ApplyCustHistory applyCustHistory = new ApplyCustHistory();
            BeanUtils.copyProperties(en, applyCustHistory);
            ApplyCustHistory custHistory = applyCustHistoryService.getById(en.getId());
            applyCustHistory.setIsLongTerm(en.getIsLongTerm());
            applyCustHistory.setCustId(en.getId());
            if (custHistory == null) {
                applyCustHistoryService.save(applyCustHistory);
            } else {
                applyCustHistoryService.updateById(applyCustHistory);
            }
            if (applyCustHistory.getContractFileVos() != null) {
                if (applyCustHistory.getCustRole().equals(ApplyConstants.PRINCIPAL_BORROWER)) {
                    queryAndRemove(applyContractInfo.getContractNo(), CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getIndex());
                    queryAndRemove(applyContractInfo.getContractNo(), CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getIndex());
                    preApproveServiceImpl.saveOrUpdateFile(applyCustHistory.getContractFileVos(), applyContractInfo.getContractNo());
                } else if (applyCustHistory.getCustRole().equals(ApplyConstants.COMMON_BORROWER)) {
                    queryAndRemove(applyContractInfo.getContractNo(), CertTypePictureEnum.COM_BORROWER_ID_CARD_FRONT.getIndex());
                    queryAndRemove(applyContractInfo.getContractNo(), CertTypePictureEnum.COM_BORROWER_ID_CARD_BACK.getIndex());
                    preApproveServiceImpl.saveOrUpdateFile(applyCustHistory.getContractFileVos(), applyContractInfo.getContractNo());
                }
            }
        });
        // GPS信息
        ApplyGpsInfo gpsInfo = vo.getGpsInfo();
        ApplyGpsInfo applyGpsInfo = applyGpsInfoService.getOne(Wrappers.<ApplyGpsInfo>query().lambda().eq(ApplyGpsInfo::getApplyNo, vo.getApplyNo()));
        if (applyGpsInfo == null) {
            gpsInfo.setApplyNo(vo.getApplyNo());
            gpsInfo.setContractNo(contractInfo.getContractNo());
            gpsInfo.setCarId(carDetails.getId().toString());
            gpsInfo.setCarVin(carDetails.getCarVin());
            applyGpsInfoService.save(gpsInfo);
        } else {
            gpsInfo.setContractNo(contractInfo.getContractNo());
            gpsInfo.setCarId(carDetails.getId().toString());
            gpsInfo.setCarVin(carDetails.getCarVin());
            BeanUtils.copyProperties(gpsInfo, applyGpsInfo);
            applyGpsInfoService.updateById(applyGpsInfo);
        }
        // 银行卡信息
        ApplyBankCard applyBankCard = applyBankCardService.getOne(Wrappers.<ApplyBankCard>query().lambda().eq(ApplyBankCard::getApplyNo, vo.getApplyNo()));
        if (vo.getBankCard().getCertNo() != null) {
            ApplyCustBaseInfo applyCustBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getCertNo, vo.getBankCard().getCertNo()).eq(ApplyCustBaseInfo::getApplyNo, vo.getApplyNo()));
            vo.getBankCard().setAccountName(applyCustBaseInfo.getCustName());
        }
        if (applyBankCard == null) {
            vo.getBankCard().setApplyNo(vo.getApplyNo());
            applyBankCardService.save(vo.getBankCard());
        } else {
            if (vo.getBankCard().getBankCode() != null && !vo.getBankCard().getBankCode().equals(applyBankCard.getBankCode() == null ? "" : applyBankCard.getBankCode())) {
                contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
            } else if (vo.getBankCard().getCertNo() != null && !vo.getBankCard().getCertNo().equals(applyBankCard.getCertNo() == null ? "" : applyBankCard.getCertNo())) {
                contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
            } else if (vo.getBankCard().getAccountNo() != null && !vo.getBankCard().getAccountNo().equals(applyBankCard.getAccountNo() == null ? "" : applyBankCard.getAccountNo())) {
                contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
            } else if (vo.getBankCard().getOpenProvince() != null && vo.getBankCard().getOpenCity() != null && (!vo.getBankCard().getOpenProvince().equals(applyBankCard.getOpenProvince() == null ? "" : applyBankCard.getOpenProvince()) || !vo.getBankCard().getOpenCity().equals(applyBankCard.getOpenCity() == null ? "" : applyBankCard.getOpenCity()))) {
                contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
            }
            BeanUtils.copyProperties(vo.getBankCard(), applyBankCard);
            applyBankCardService.updateById(applyBankCard);
        }
        ApplyCarDetails carDetailsServiceOne = applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda().eq(ApplyCarDetails::getApplyNo, vo.getApplyNo()));

        if (vo.getInsuranceInfos().size() > 0) {
            List<ApplyInsuranceInfo> applyInsuranceInfo = applyInsuranceInfoService.list(Wrappers.<ApplyInsuranceInfo>query().lambda()
                    .eq(ApplyInsuranceInfo::getApplyNo, vo.getInsuranceInfos().get(0).getApplyNo()));
            if (applyInsuranceInfo.size() > 0) {
                for (int i = 0; i < applyInsuranceInfo.size(); i++) {
                    applyInsuranceInfoService.removeById(applyInsuranceInfo.get(i).getId());
                }
            }
            vo.getInsuranceInfos().forEach(en -> {
                en.setId(null);
                en.setCarId(carDetailsServiceOne.getId().toString());
                en.setCarVin(carDetailsServiceOne.getCarVin());
                applyInsuranceInfoService.save(en);
            });
        }
        //个体工商户挂靠需要保存
        if ((AffiliatedUnitEnum.person.getCode()).equals(vo.getOrderInfo().getAffiliatedWay())) {
            vo.getAffiliatedUnit().setModifyFlag("1");
            if (vo.getAffiliatedUnit().getId() == null) {
                applyAffiliatedUnitService.save(vo.getAffiliatedUnit());
            } else {
                applyAffiliatedUnitService.updateById(vo.getAffiliatedUnit());
            }
        }
        // 增融项
        vo.getFinancingItems().forEach(en -> {
            ApplyAddPriceItems item = new ApplyAddPriceItems();
            BeanUtils.copyProperties(en, item);
            item.setCarId(String.valueOf(carDetailsServiceOne.getId()));
            item.setContractNo(contractInfo.getContractNo());
            item.setAddFinanceAmt(en.getFinanceItemAmt());
            ApplyAddPriceItems applyAddPriceItems = applyAddPriceItemsService.getById(item.getId());
            if (applyAddPriceItems != null) {
                if ((en.getFinanceItemAmt() == null ? BigDecimal.ZERO : en.getFinanceItemAmt()).compareTo(applyAddPriceItems.getAddFinanceAmt() == null ? BigDecimal.ZERO : applyAddPriceItems.getAddFinanceAmt()) != 0) {
                    contractInfo.setReappearFlag(ApplyConstants.APP_FORM_STATE_ONE);
                }
            }
            applyAddPriceItemsService.saveOrUpdate(item);
        });
        if (applyContractInfo == null) {
            applyContractInfoService.save(contractInfo);
        } else {
            BeanUtils.copyProperties(contractInfo, applyContractInfo);
            if (StringUtils.isEmpty(applyContractInfo.getCreateBy()) || ApplyConstants.APPLY_USER.equals(applyContractInfo.getCreateBy())) {
                applyContractInfo.setCreateBy(SecurityUtils.getUsername());
            }
            applyContractInfo.setSellerRealName(SecurityUtils.getUser().getUserRealName()+"("+SecurityUtils.getUsername()+")");
            applyContractInfoService.updateById(applyContractInfo);
        }
        return new IResponse().setMsg("保存成功");
    }

    @PostMapping(value = "/getChannelBaseInfo")
    @ApiOperation(value = "获取挂靠信息")
    public IResponse getChannelBaseInfo(@RequestBody ChannelCondition condition) {
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", config.getChannelClientId());
        requestHeader.put("clientSecret", config.getChannelClientSecret());
        return apply2ChannelFeign.getChannelBaseInfo(condition, requestHeader);
    }

    /**
     * GPS首次派单
     *
     * @param gpsInfo
     * @return
     */
    @Transactional
    @PostMapping("/distribute")
    @ApiOperation(value = "GPS派单")
    public IResponse distribute(@RequestBody GpsCondition gpsInfo) {
        //VIN校验
//        Boolean flag= VinUtils.isValidVin(gpsInfo.getCarVin());
//        if(!flag){
//            return  new IResponse().setCode(CommonConstants.FAIL).setMsg("车架号格式不正确");
//        }
        GpsProductInfo gpsProductInfo = gpsProductInfoService.getOne(Wrappers.<GpsProductInfo>query().lambda()
                .lt(GpsProductInfo::getDownTerm, gpsInfo.getLoanTerm())
                .ge(GpsProductInfo::getUpTerm, gpsInfo.getLoanTerm())
                .eq(GpsProductInfo::getGpsType, gpsInfo.getGpsType())
                .eq(GpsProductInfo::getGpsFirm, gpsInfo.getGpsSupplier()));
        if (gpsProductInfo == null) {
            return new IResponse().setCode(CommonConstants.FAIL).setMsg("未匹配到GPS产品");
        }
        gpsInfo.setGpsProductNo(gpsProductInfo.getGpsProductId());
        GpsInstallVO installVO = applyGpsInfoService.getGpsPreInstallInfo(gpsInfo);
        // 调用GPS派单
        JSONObject result = applyGpsInfoService.addOrderWithVpsInfos(gpsInfo, installVO);
        Boolean success = result.getBoolean("Success");
        if (success) {
            gpsInfo.setOrderNo(result.getJSONObject("Data").getString("Id"));
            ApplyGpsInfo applyGpsInfo = applyGpsInfoService.getOne(Wrappers.<ApplyGpsInfo>query().lambda().eq(ApplyGpsInfo::getApplyNo, gpsInfo.getApplyNo()));
            if (applyGpsInfo == null) {
                applyGpsInfoService.save(gpsInfo);
            } else {
                Long id = applyGpsInfo.getId();
                BeanUtils.copyProperties(gpsInfo, applyGpsInfo);
                applyGpsInfo.setId(id);
                applyGpsInfoService.updateById(applyGpsInfo);
            }
            ApplyContractInfo applyContractInfo = applyContractInfoService.getContractInfoByAppplyNo(gpsInfo.getApplyNo());
            applyContractInfo.setGpsStatus(ApplyConstants.SEND_TASK);
            applyContractInfoService.updateById(applyContractInfo);
            return new IResponse().setCode(CommonConstants.SUCCESS).setMsg("派单成功");
        } else {
            return new IResponse().setCode(CommonConstants.FAIL).setMsg(result.getString("AllMessages"));
        }
    }

    @PostMapping("/getCustChange")
    @ApiOperation(value = "查询客户信息变更记录")
    public IResponse getCustChange(@RequestBody ApplyCustBaseInfo custBaseInfo) {

        ApplyCustHistory custHistory = applyCustHistoryService.getOne(Wrappers.<ApplyCustHistory>query().lambda()
                .eq(ApplyCustHistory::getCustId, custBaseInfo.getId()));
        if (custHistory == null) {
            custHistory = new ApplyCustHistory();
            BeanUtils.copyProperties(custBaseInfo, custHistory);
            custHistory.setCustId(custBaseInfo.getId());
            custHistory.setCertStartDate(null);
            custHistory.setCertEndDate(null);
            custHistory.setIsLongTerm(null);
            custHistory.setId(null);
        }
        return new IResponse().setData(custHistory);
    }

    @Transactional
    @PostMapping("/saveCert")
    @ApiOperation(value = "保存客户证件信息")
    public IResponse saveCert(@RequestBody ApplyCustHistory custHistory) {
        boolean result;
        if (custHistory.getId() == null) {
            result = applyCustHistoryService.save(custHistory);
        } else {
            result = applyCustHistoryService.updateById(custHistory);
        }
        if (result) {
            return new IResponse().setMsg("保存成功").setData(custHistory);
        } else {
            return new IResponse().setCode(errorCode).setMsg("保存失败");
        }
    }

    @PostMapping("/commitEditStatus")
    @ApiOperation(value = "修改合同状态")
    public IResponse commitEditStatus(@RequestBody ApplyOrderInfo applyOrderInfo) {
        WitnessInfo witnessInfo = new WitnessInfo();
        witnessInfo.setChannelId(SecurityUtils.getUser().getUserExtInfo().getLong("channelId"));
        JSONObject jsonObject = applyContractInfoServiceImpl.getWitnessInfo(witnessInfo);
        if (CommonConstants.SUCCESS.equals(jsonObject.getString("code"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            List<WitnessInfo> witnessInfos = JSON.parseArray(jsonArray.toJSONString(), WitnessInfo.class);
            if (witnessInfos.size() == 0) {
                return new IResponse().setCode(CommonConstants.FAIL).setMsg("见证人不能为空");
            }
        }
        ApplyGpsInfo applyGpsInfo = applyGpsInfoService.getOne(Wrappers.<ApplyGpsInfo>query().lambda().eq(ApplyGpsInfo::getApplyNo, applyOrderInfo.getApplyNo()));
        ApplyGpsOrderHistory applyGpsOrderHistory = new ApplyGpsOrderHistory();
        BeanUtils.copyProperties(applyGpsInfo, applyGpsOrderHistory);
        applyGpsOrderHistory.setInstallTime(applyGpsInfo.getPreInstallTime());
        applyGpsOrderHistoryService.saveOrUpdate(applyGpsOrderHistory);
        ApplyContractInfo applyOrderInfo1 = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                .eq(ApplyContractInfo::getApplyNo, applyOrderInfo.getApplyNo()));
        if (applyOrderInfo1.getLendingFirstDate() == null) {
            applyOrderInfo1.setLendingFirstDate(new Date());
        }
        applyOrderInfo1.setDeptId(SecurityUtils.getUser().getDeptId().toString());
        applyOrderInfo1.setLoanReporter(SecurityUtils.getUser().getUsername());
        applyOrderInfo1.setContractStatus(ApplyConstants.CONTRACT_STATUS_SUBMIT);
        boolean result = applyContractInfoService.updateById(applyOrderInfo1);
        if (result) {
            return new IResponse().setMsg("保存成功");
        } else {
            return new IResponse().setCode(errorCode).setMsg("保存失败");
        }
    }

    @PostMapping("/queryWitnessIdCard")
    @ApiOperation(value = "判断见证人是否有见证记录")
    public IResponse queryWitnessIdCard(@RequestBody List<String> cards) {
        if (ObjectUtils.isEmpty(cards)) {
            return new IResponse().fail("见证人证件号码不能为空");
        }
        List<ApplyContractInfo> users = applyContractInfoService.list(Wrappers.<ApplyContractInfo>query().lambda()
                .in(ApplyContractInfo::getWitnessIdCard, cards)
                .notIn(ApplyContractInfo::getContractStatus, ApplyConstants.CONTRACT_STATUS_PASS));
        return IResponse.success(users);
    }

    /**
     * 转单
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/transferData")
    @ApiOperation("转单")
    public IResponse transferData(@RequestBody OrderOprCondition condition) {
        //更新订单操作表
        ApplyOprRecord applyOprRecord = new ApplyOprRecord();
        applyOprRecord.setApplyNo(condition.getApplyNo());
        applyOprRecord.setCreateBy(SecurityUtils.getUsername());
        applyOprRecord.setCreateTime(new Date());
        applyOprRecord.setApplyType(OrderOprType.TRANSFER);
        this.applyOprRecordService.save(applyOprRecord);
        //更新订单表的createBy,也就是录单员
        ApplyContractInfo applyContractInfo = this.applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                .eq(ApplyContractInfo::getApplyNo, condition.getApplyNo()));
        applyContractInfo.setCreateBy(condition.getCreateBy());
        applyContractInfo.setUpdateTime(condition.getUpdateTime());
        boolean b = this.applyContractInfoService.updateById(applyContractInfo);
        if (b) {
            return IResponse.success("转单成功");
        }
        return IResponse.success("转单失败");
    }


    /**
     * 判断是否保存全部信息
     **/
    @PostMapping("/queryAllInfo")
    @ApiOperation(value = "判断全部信息")
    public IResponse queryAllInfo(@RequestParam("applyNo") String applyNo) {
        ApplyOrderInfo orderInfoByApplyNo = applyOrderInfoService.getOrderInfoByApplyNo(applyNo);
        if (ObjectUtil.isNull(orderInfoByApplyNo)) {
            return new IResponse().fail("生成模板失败:订单信息不存在");
        }
        //车辆信息
        ApplyCarDetails applyCarDetails = applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda()
                .eq(ApplyCarDetails::getApplyNo, applyNo));
        if (ObjectUtil.isNull(applyCarDetails)) {
            return new IResponse().fail("生成模板失败:车辆信息不存在");
        }
        //根据申请编号查询客户基础信息
        List<ApplyCustBaseInfo> applyCustBaseInfoList = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, applyNo));
        if (CollectionUtil.isEmpty(applyCustBaseInfoList)) {
            return new IResponse().fail("生成模板失败:客户基础信息不存在");
        }
        //获取地址信息,根据applyNo
        List<ApplyCustAddressDetails> applyCustAddressDetailsList = applyCustAddressDetailsService.list(Wrappers.<ApplyCustAddressDetails>query().lambda()
                .eq(ApplyCustAddressDetails::getApplyNo, applyNo));
        if (CollectionUtil.isEmpty(applyCustAddressDetailsList)) {
            return new IResponse().fail("生成模板失败:地址信息不存在");
        }
        //获取客户联系人信息list
        List<ApplyCustContacts> applyCustContactsList = applyCustContactsService.list(Wrappers.<ApplyCustContacts>query().lambda()
                .eq(ApplyCustContacts::getApplyNo, applyNo));
        if (CollectionUtil.isEmpty(applyCustContactsList)) {
            return new IResponse().fail("生成模板失败:客户联系人信息不存在");
        }
        //融资信息
        List<FinCostDetails> applyCostDetailsList = this.applyCostDetailsService.list(Wrappers.<FinCostDetails>query().lambda()
                .eq(FinCostDetails::getApplyNo, applyNo));
        if (CollectionUtil.isEmpty(applyCostDetailsList)) {
            return new IResponse().fail("生成模板失败:融资信息不存在");
        }
        return IResponse.success("查询成功");
    }

    @PostMapping("/getGpsAgainInfo")
    @ApiOperation("获取二次派单列表")
    public IResponse<IPage<List<ApplyContractInfo>>> getGpsAgainInfo(@RequestBody ContractCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        condition.setGpsStatus(ApplyConstants.UN_PASS_AUDIT);
        IPage<List<ApplyContractInfo>> list = contractMngServiceImpl.getGpsAgainInfo(condition, page);
        return IResponse.success(list);
    }

    @PostMapping("/getPendingInfo")
    @ApiOperation("获取待办信息")
    public IResponse getPendingInfo(@RequestBody ApplyTotalCondition applyTotalCondition) {
        if (applyTotalCondition.getChannelId() == null || applyTotalCondition.getChannelId().equals("")) {
            return new IResponse().fail("渠道id不能为空");
        }
        Map pendingMap = new HashMap();
        List<ApplyOrderInfo> applyOrderInfoList = new ArrayList();
        List<ApplyOrderInfo> applyOrderInfos = new ArrayList();
        List<ApplyOrderInfo> applyOprRecords = new ArrayList();
        List<ApplyOrderInfo> applyOrders=new ArrayList();
        List<ApplyContractInfo> applyContractInfoList = new ArrayList();
        List<ApplyContractInfo> applyContractInfos = new ArrayList();
        List<ApplyContractInfo> applyContractInfos1 = new ArrayList();
        List<ApplyOprRecord> applyOrderInfo=new ArrayList();
        JSONArray roleArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("roles");
        if (roleArray != null) {
            if (roleArray.toString().indexOf(ApplyConstants.ROLE_ADMIN) > -1) {
                return IResponse.success(pendingMap);
            }
            if (roleArray.toString().indexOf(ApplyConstants.ROLE_XCAPPLY) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_XCRECORDED) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_CHANNEL_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_CHANNEL_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_RECORDED) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_APPLY) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_DIRECT_ADMIN) > -1|| roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_DIRECT_ADMIN) > -1) {
                //进件申请草稿
                applyOrderInfoList = applyOrderInfoService.getDefaultList(applyTotalCondition.getChannelId(), ApplyConstants.APPLY_STATUS_DRAFT);
                //进件申请修订暂停
                applyOrderInfos = applyOrderInfoService.getDefaultList(applyTotalCondition.getChannelId(), ApplyConstants.APPLY_STATUS_SUSPEND);
                //复议-补录资料
                applyOprRecords = applyOrderInfoService.getDefaultList(applyTotalCondition.getChannelId(), ApplyConstants.APPLY_STATUS_REVIEWPENDINGSUBMISSION);
                //附条件核准
                applyOrders=applyOrderInfoService.getDefaultList(applyTotalCondition.getChannelId(),ApplyConstants.APPLY_STATUS_CONDITION);
                //贷前资产变更1
                applyOrderInfo = applyOprRecordService.oprInfoForReconsider(applyTotalCondition.getChannelId(),ApplyConstants.APPLY_STATUS_ASSERT_CHANGE);

            }
            if (roleArray.toString().indexOf(ApplyConstants.ROLE_XCPAYMENT) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_CHANNEL_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_XCPREPAYMENT) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_PAYMENT) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_CHANNEL_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_PREPAYMENT) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_DIRECT_ADMIN) > -1|| roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_DIRECT_ADMIN) > -1) {
                //放款待提交
                applyContractInfoList = applyContractInfoService.getDefaultList(applyTotalCondition.getChannelId(), ApplyConstants.CONTRACT_STATUS_01, "");
                //放款已退回
                applyContractInfos = applyContractInfoService.getDefaultList(applyTotalCondition.getChannelId(), ApplyConstants.CONTRACT_STATUS_BACK, "");
                //GPS二次派单
                applyContractInfos1 = applyContractInfoService.getDefaultList(applyTotalCondition.getChannelId(), "", ApplyConstants.UN_PASS_AUDIT);

            }
        }

        //消息未读
        List<TsysMessageNotify> tsysMessageNotifyList = applyMessageNotifyService.list(Wrappers.<TsysMessageNotify>query().lambda()
                .eq(TsysMessageNotify::getChannelId, applyTotalCondition.getChannelId()).eq(TsysMessageNotify::getStatus, IsReadStatusEnum.UNREAD.getIndex()));
        if (roleArray.toString().indexOf(ApplyConstants.ROLE_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_APPLY) > -1
                || roleArray.toString().indexOf(ApplyConstants.ROLE_XCAPPLY) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_RECORDED) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_XCRECORDED) > -1
                || roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_CHANNEL_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_CHANNEL_ADMIN) > -1 ||
        roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_DIRECT_ADMIN) > -1|| roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_DIRECT_ADMIN) > -1) {
            pendingMap.put("draft", applyOrderInfoList.size());
            pendingMap.put("suspend", applyOrderInfos.size());
        }
        if (roleArray.toString().indexOf(ApplyConstants.ROLE_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_APPLY) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_XCAPPLY) > -1
                || roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_CHANNEL_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_CHANNEL_ADMIN) > -1 ||
                roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_DIRECT_ADMIN) > -1|| roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_DIRECT_ADMIN) > -1) {
            pendingMap.put("condition",applyOrders.size());
            pendingMap.put("refuse", applyOprRecords.size());
            pendingMap.put("pass", applyOrderInfo.size());
        }
        if (roleArray.toString().indexOf(ApplyConstants.ROLE_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_PREPAYMENT) > -1
                || roleArray.toString().indexOf(ApplyConstants.ROLE_PAYMENT) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_XCPREPAYMENT) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_XCPAYMENT) > -1
                || roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_CHANNEL_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_CHANNEL_ADMIN) > -1 ||
                roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_DIRECT_ADMIN) > -1|| roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_DIRECT_ADMIN) > -1) {
            pendingMap.put("wait", applyContractInfoList.size());
            pendingMap.put("back", applyContractInfos.size());
        }
        if (roleArray.toString().indexOf(ApplyConstants.ROLE_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_PAYMENT) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_XCPAYMENT) > -1
                || roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_CHANNEL_ADMIN) > -1 || roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_CHANNEL_ADMIN) > -1 ||
                roleArray.toString().indexOf(ApplyConstants.ROLE_NEW_DIRECT_ADMIN) > -1|| roleArray.toString().indexOf(ApplyConstants.ROLE_OLD_DIRECT_ADMIN) > -1) {
            pendingMap.put("again", applyContractInfos1.size());
        }
//        pendingMap.put("unread", tsysMessageNotifyList.size());
        pendingMap.put("sign", 0);
        return IResponse.success(pendingMap);
    }

    @PostMapping("/getTotalInfo")
    @ApiOperation("获取统计数据")
    public IResponse getTotalInfo(@RequestBody ApplyTotalCondition applyTotalCondition) {
        if (applyTotalCondition.getChannelId() == null || applyTotalCondition.getChannelId().equals("")) {
            return new IResponse().fail("渠道id不能为空");
        }
        if (applyTotalCondition.getType() == null || applyTotalCondition.getType().equals("")) {
            return new IResponse().fail("查询类型不能为空");
        }
        Map countMap = new HashMap();
        //进件申请数
        List<ApplyOrderInfo> applyOrderInfoList = applyOrderInfoService.getApplyCount(applyTotalCondition);
        //放款申请数
        List<ApplyContractInfo> applyContractInfoList = applyContractInfoService.getContractCount(applyTotalCondition);
        //融资额
        List<FinCostDetails> finCostDetailsList = applyCostDetailsService.getAllMoney(applyTotalCondition);
        BigDecimal money = BigDecimal.ZERO;
        if (finCostDetailsList.size() > 0) {
            for (FinCostDetails finCostDetails : finCostDetailsList) {
                money = money.add(finCostDetails.getLoanAmt());
            }
        }
        countMap.put("applyCount", applyOrderInfoList.size());
        countMap.put("contractCount", applyContractInfoList.size());
        countMap.put("loanMoney", money);
        return IResponse.success(countMap);
    }

    /**
     * OCR识别
     */
    @PostMapping("/getOCRInfo")
    @ApiOperation("OCR识别")
    public IResponse getMd5Info(@RequestBody OcrDiscernCondition condition) {
        JSONObject jsonObject = null;
        String value = tSysParamConfigService.getParamValue("OCR", "number", "0");
        if (!value.equals(ApplyConstants.YES)) {
            log.info("聚合接口关闭");
            return IResponse.success(jsonObject);
        }
        if (condition.getFileCode().equals("bankCard")) {
            jsonObject = ocrDiscernService.bankCardOcrDiscern(condition);
        } else if (condition.getFileCode().equals("invoiceCar")) {
            jsonObject = ocrDiscernService.invoiceCarOcrDiscern(condition);
        } else if (condition.getFileCode().equals("idCardFront")) {
            jsonObject = ocrDiscernService.idCardFrontOcrDiscern(condition);
        } else if (condition.getFileCode().equals("idCardBack")) {
            jsonObject = ocrDiscernService.idCardBackOcrDiscern(condition);
        }
        if (jsonObject.getString("code").equals("200")) {
            return IResponse.success(jsonObject.get("data"));
        } else {
            return new IResponse().setCode(errorCode).setMsg(jsonObject.getString("msg"));
        }
    }

    /**
     * 合同录入上传附件
     */
    @PostMapping("/uploadFile")
    @ApiOperation("合同录入上传附件")
    public IResponse uploadFile(@RequestBody ContractFileCondition condition) {
        this.preApproveService.storeCardImage(condition.getFrontIDCard(), condition.getReverseIDCard(), condition.getUploadScene(), condition.getCustRole(), String.valueOf(condition.getId()));
        return IResponse.success("上传成功");
    }

    /**
     * 合同录入单个文件生成MD5
     */
    @PostMapping("/fileToMD5")
    @ApiOperation("合同录入单个文件生成MD5")
    public IResponse fileToMD5(@RequestBody MultipartFile file) {
        Map<String, String> headers = new HashMap<>(3);
        headers.put("Authorization", this.imageUploadUtil.getAuthorization());
        ContractFileVo contractFileVo = imageUploadUtil.doUploadNew(file, headers);
        return IResponse.success(contractFileVo);
    }

    /**
     * 合同录入单个文件上传
     */
    @PostMapping("/uploadOneFile")
    @ApiOperation("合同录入上传附件")
    public IResponse uploadOneFile(@RequestBody ContractFileCondition condition) {
        Map<String, String> headers = new HashMap<>(3);
        headers.put("Authorization", this.imageUploadUtil.getAuthorization());
        byte[] fileByte = imageStoreApiFeign.downFile(condition.getMap().get("md5").toString(), fastdfsProperties.getSceneId(), "", IsViewEnum.download.getCode(), null, headers);
        return IResponse.success(fileByte);
    }

    /**
     * 合同录入单个文件上传
     */
    @PostMapping("/uploadMoreFile")
    @ApiOperation("合同录入上传附件")
    public IResponse uploadMoreFile(@RequestBody ContractFileCondition condition) {
        preApproveServiceImpl.saveOrUpdateFile(condition.getContractFileVos(), condition.getBusiNo());
        return IResponse.success("上传成功");
    }

    /**
     * md5获取base64
     */
    @PostMapping("/getBaseByMD5")
    @ApiOperation("合同录入上传附件")
    public IResponse getBaseByMD5(@RequestBody ContractFileCondition condition) {
        Map map = new HashMap();
        List<ComAttachmentFile> frontFile = null;
        List<ComAttachmentFile> blackFile = null;
        ComAttachmentManagement frontManagement = this.managementMapper.selectOne(Wrappers.<ComAttachmentManagement>query().lambda().eq(ComAttachmentManagement::getUniqueCode, condition.getFront()));
        if (frontManagement != null) {
            frontFile = this.comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo, condition.getBusiNo())
                    .eq(StringUtil.isNotEmpty(frontManagement.getAttachmentName()), ComAttachmentFile::getAttachmentName, frontManagement.getAttachmentName()));
            if (frontFile != null) {
                map.put("front", frontFile);
            }
        }
        ComAttachmentManagement blackManagement = this.managementMapper.selectOne(Wrappers.<ComAttachmentManagement>query().lambda().eq(ComAttachmentManagement::getUniqueCode, condition.getBlack()));
        if (blackManagement != null) {
            blackFile = this.comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo, condition.getBusiNo())
                    .eq(StringUtil.isNotEmpty(blackManagement.getAttachmentName()), ComAttachmentFile::getAttachmentName, blackManagement.getAttachmentName()));
            if (blackFile != null) {
                map.put("black", blackFile);
            }
        }
        return IResponse.success(map);
    }

    public String queryAndRemove(String id, String type) {
        ComAttachmentManagement comAttachmentManagement = this.managementMapper.selectOne(Wrappers.<ComAttachmentManagement>query().lambda()
                .eq(ComAttachmentManagement::getUniqueCode, type));
        //先查询
        List<ComAttachmentFile> attachmentFile = this.comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo, id).eq(ComAttachmentFile::getAttachmentCode, comAttachmentManagement.getId().toString()));
        if (attachmentFile.size() > 0) {
            for (ComAttachmentFile comAttachmentFile1 : attachmentFile) {
                this.comAttachmentFileService.removeById(comAttachmentFile1);
                log.info("{}", comAttachmentFile1.getId() + "删除成功");
            }
        }
        return null;
    }


    @PostMapping(value = "/getdrawerPartyByChannelId")
    @ApiOperation(value = "获取开票单位信息")
    public IResponse getdrawerPartyByChannelId(@RequestBody DrawerCondition condition) {
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", config.getCaseClientId());
        requestHeader.put("clientSecret", config.getCaseClientSecret());
        return apply2ChannelFeign.getdrawerPartyByChannelId(condition, requestHeader);
    }
    @PostMapping(value = "/getIsFirstMortgage")
    @ApiOperation(value = "获取首单模式")
    public IResponse getIsFirstMortgage(@RequestBody ContractCondition condition) {
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", config.getCaseClientId());
        requestHeader.put("clientSecret", config.getCaseClientSecret());
        ContractModelCondition contractModelCondition=new ContractModelCondition();
        contractModelCondition.setApplyNo(condition.getApplyNo());
       return apply2ChannelFeign.getIsFirstMortgage(contractModelCondition, requestHeader);

    }

    @PostMapping(value = "/getWitnessInfo")
    @ApiOperation(value = "获取见证人列表")
    public IResponse getWitnessInfo(@RequestBody ChannelWitnessCondition condition) {
        WitnessInfo witnessInfo = new WitnessInfo();
        List<WitnessInfo> witnessInfos = null;
        if (ApplyConstants.BUSINESS_TYPE_NEW_CAR.equals(condition.getBusinessAttributes())) {
            witnessInfo.setBusinessAttributes(ApplyConstants.WITNESS_NEW_CAR);
        } else {
            witnessInfo.setBusinessAttributes(ApplyConstants.WITNESS_OLD_CAR);
        }
        witnessInfo.setChannelId(SecurityUtils.getUser().getUserExtInfo().getLong("channelId"));
        JSONObject jsonObject = applyContractInfoServiceImpl.getWitnessInfo(witnessInfo);
        if (CommonConstants.SUCCESS.equals(jsonObject.getString("code"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            witnessInfos = JSON.parseArray(jsonArray.toJSONString(), WitnessInfo.class);
        }
        return IResponse.success(witnessInfos);
    }


    @PostMapping("/getTotalInfoForPc")
    @ApiOperation("获取统计数据")
    public IResponse getTotalInfoForPc(@RequestBody ApplyTotalCondition applyTotalCondition) {
        if (applyTotalCondition.getChannelId() == null || applyTotalCondition.getChannelId().equals("")) {
            return new IResponse().fail("渠道id不能为空");
        }
        Map countMap = new HashMap();
        //进件申请数
        List<ApplyStatisticsVo> applyOrderInfoList = applyOrderInfoService.getApplyCountPc(applyTotalCondition);
        //放款申请数
        List<ApplyStatisticsVo> applyContractInfoList = applyContractInfoService.getContractCountPc(applyTotalCondition);
        if (applyOrderInfoList != null && applyContractInfoList != null) {
            List order = new ArrayList();
            List contract = new ArrayList();
            for (ApplyStatisticsVo applyVo : applyOrderInfoList) {
                order.add(applyVo.getType());
            }
            for (ApplyStatisticsVo contractVo : applyContractInfoList) {
                contract.add(contractVo.getType());
            }
            List add = new ArrayList(order);
            add.removeAll(contract);
            List add2 = new ArrayList(contract);
            add2.removeAll(order);
            if (add != null) {
                for (int i = 0; i < add.size(); i++) {
                    ApplyStatisticsVo applyStatisticsVo = new ApplyStatisticsVo();
                    applyStatisticsVo.setType(add.get(i).toString());
                    applyStatisticsVo.setAccount(0);
                    applyContractInfoList.add(applyStatisticsVo);
                }
            }
            if (add2 != null) {
                for (int i = 0; i < add2.size(); i++) {
                    ApplyStatisticsVo applyStatisticsVo = new ApplyStatisticsVo();
                    applyStatisticsVo.setType(add2.get(i).toString());
                    applyStatisticsVo.setAccount(0);
                    applyOrderInfoList.add(applyStatisticsVo);
                }
            }
        } else if (applyOrderInfoList != null && applyContractInfoList == null) {
            List order = new ArrayList();
            for (ApplyStatisticsVo applyVo : applyOrderInfoList) {
                order.add(applyVo.getType());
            }
            for (int i = 0; i < order.size(); i++) {
                ApplyStatisticsVo applyStatisticsVo = new ApplyStatisticsVo();
                applyStatisticsVo.setType(order.get(i).toString());
                applyStatisticsVo.setAccount(0);
                applyContractInfoList.add(applyStatisticsVo);
            }
        } else if (applyOrderInfoList == null && applyContractInfoList != null) {
            List contract = new ArrayList();
            for (ApplyStatisticsVo contractVo : applyContractInfoList) {
                contract.add(contractVo.getType());
            }
            for (int i = 0; i < contract.size(); i++) {
                ApplyStatisticsVo applyStatisticsVo = new ApplyStatisticsVo();
                applyStatisticsVo.setType(contract.get(i).toString());
                applyStatisticsVo.setAccount(0);
                applyOrderInfoList.add(applyStatisticsVo);
            }
        }
        if (applyOrderInfoList != null && applyContractInfoList != null) {
            Collections.sort(applyOrderInfoList, (o1, o2) -> {
                int i = Integer.parseInt(o1.getType()) - Integer.parseInt(o2.getType());
                return i;
            });
            Collections.sort(applyContractInfoList, (o1, o2) -> {
                int i = Integer.parseInt(o1.getType()) - Integer.parseInt(o2.getType());
                return i;
            });
        }
        countMap.put("applyCount", applyOrderInfoList);
        countMap.put("contractCount", applyContractInfoList);
        return IResponse.success(countMap);
    }

    /**
     * 保存备注
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "updateWitnesses")
    @ApiOperation("更新见证人信息")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_contract_info", allEntries = true)
    public IResponse updateWitnesses(@RequestBody ContractCondition condition) {

        ApplyContractInfo contractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda().eq(ApplyContractInfo::getApplyNo, condition.getApplyNo()));
        if (contractInfo != null) {
            contractInfo.setWitnessIdCard(condition.getWitnessIdCard());
            contractInfo.setWitnessName(condition.getWitnessName());
            applyContractInfoService.updateById(contractInfo);
        } else {
            return IResponse.fail("合同信息不存在");
        }
        return IResponse.success(Boolean.TRUE);
    }

    @PostMapping(value = "/getIdCardInfo")
    @ApiOperation("根据身份证号获取订单信息")
    public IResponse<ApplyIdCardInfoDTO> getIdCardInfo(@RequestBody ApplyIdCardDTO condition) {
        log.info("--------------------进件系统根据身份证号获取订单信息入参为证件号：[{}],申请编号：[{}]",condition.getIdCard(),condition.getApplicationNo());
        if((EmptyUtils.isEmpty(condition.getIdCard())||"null".equals(condition.getIdCard()))&&(EmptyUtils.isEmpty(condition.getApplicationNo())||"null".equals(condition.getApplicationNo()))){
            return IResponse.fail("身份证号、合同号不能同时为空");
        }
        ApplyIdCardInfoDTO applyIdCardInfoVo = new ApplyIdCardInfoDTO();
        String phone = "";
        if(!ObjectUtils.isEmpty(condition.getApplicationNo())){
            log.info("--------------------件系统根据身份证号获取订单信息，使用证件号查询数据--------------------");
            List<ApplyCustBaseInfo> custBaseInfoList = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                    .eq(ApplyCustBaseInfo::getCertNo, condition.getIdCard()).eq(ApplyCustBaseInfo::getCustRole,ApplyConstants.PRINCIPAL_BORROWER));
            if (!ObjectUtils.isEmpty(custBaseInfoList)&&custBaseInfoList.size() > 0) {
                for (ApplyCustBaseInfo applyCustBaseInfo : custBaseInfoList) {
                    if (!ObjectUtils.isEmpty(applyCustBaseInfo.getTelPhone())) {
                        phone += applyCustBaseInfo.getTelPhone() + ",";
                    }
                }
                applyIdCardInfoVo.setOriginalPhone(phone);
                applyIdCardInfoVo.setCustomerStatus(ApplyConstants.CUSTOMER_STATUS);
                applyIdCardInfoVo.setSpecialStatus(ApplyConstants.SPECIAL_STATUS);
                applyIdCardInfoVo.setIdCard(condition.getApplicationNo());
            }
        }else{
            log.info("--------------------件系统根据身份证号获取订单信息，使用申请单号查询数据--------------------");
            ApplyCustBaseInfo applyCustBaseInfo = applyCustBaseInfoService.getCustBaseInfo(condition.getApplicationNo(),ApplyConstants.PRINCIPAL_BORROWER);
            if (!ObjectUtils.isEmpty(applyCustBaseInfo)) {
                if (!ObjectUtils.isEmpty(applyCustBaseInfo.getTelPhone())) {
                    applyIdCardInfoVo.setOriginalPhone(applyCustBaseInfo.getTelPhone());
                    applyIdCardInfoVo.setCustomerStatus(ApplyConstants.CUSTOMER_STATUS);
                    applyIdCardInfoVo.setSpecialStatus(ApplyConstants.SPECIAL_STATUS);
                    applyIdCardInfoVo.setIdCard(applyCustBaseInfo.getCertNo());
                }
            }
        }

        return IResponse.success(applyIdCardInfoVo);
    }

    /**
     * 获取GPS全称
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getGpsFullName")
    @ApiOperation("获取GPS全称")
    public IResponse getGpsFullName(@RequestBody GpsProductCondition condition) {
        GpsProductInfo gpsProductInfo = gpsProductInfoService.getOne(Wrappers.<GpsProductInfo>query().lambda()
                .lt(GpsProductInfo::getDownTerm, condition.getDownTerm())
                .ge(GpsProductInfo::getUpTerm, condition.getDownTerm())
                .eq(GpsProductInfo::getGpsType, condition.getGpsType())
                .eq(GpsProductInfo::getGpsFirm, condition.getGpsFirm()));
        return IResponse.success(gpsProductInfo);
    }

    /**
     * 审批记录查询
     * */
    @PostMapping(value = "/getApprovalRecord")
    @ApiOperation("获取审批记录")
    public IResponse getApprovalRecord(@RequestParam("applyNo") String applyNo){
        ApprovalRecordVo approvalRecordVo=new ApprovalRecordVo();
        approvalRecordVo.setApplyNo(applyNo);
        ApplyCarDetails applyCarDetails=applyCarDetailsService.getCarDetailsByApplyNo(applyNo);
        if(applyCarDetails!=null){
            approvalRecordVo.setBrandName(applyCarDetails.getBrandName());
            approvalRecordVo.setModelName(applyCarDetails.getModelName());
            approvalRecordVo.setStyleName(applyCarDetails.getStyleName());
        }
        BigDecimal money=BigDecimal.ZERO;
        List<FinCostDetails> costDetailsList=applyCostDetailsService.getCostDetailsList(applyNo);
        if(costDetailsList.size()>0){
            approvalRecordVo.setLoanTerm(costDetailsList.get(0).getLoanTerm());
            for(FinCostDetails costDetails:costDetailsList){
                money=money.add(costDetails.getLoanAmt()==null?BigDecimal.ZERO:costDetails.getLoanAmt());
            }
            approvalRecordVo.setLoanAmt(money);
        }
        ApplyOrderInfo applyOrderInfo=applyOrderInfoService.getOrderInfoByApplyNo(applyNo);
        ApplyContractInfo applyContractInfo=applyContractInfoService.getContractInfoByAppplyNo(applyNo);
        if(applyContractInfo!=null){
            if(applyContractInfo.getStartDate()!=null){
                approvalRecordVo.setContractStart(applyContractInfo.getStartDate());
            }
            if(applyContractInfo.getLendingPassDate()!=null){
                approvalRecordVo.setContractApproval(applyContractInfo.getLendingPassDate());
            }
            if(applyContractInfo.getCancelDate()!=null){
                approvalRecordVo.setContractCancel(applyContractInfo.getCancelDate());
            }
            if(applyContractInfo.getLendingFirstDate()!=null){
                approvalRecordVo.setContractCommit(applyContractInfo.getLendingFirstDate());
            }
        }
        if(applyOrderInfo!=null){
            approvalRecordVo.setCustName(applyOrderInfo.getCustName());
            if(applyOrderInfo.getRiskPassDate()!=null){
                approvalRecordVo.setOrderRisk(applyOrderInfo.getRiskPassDate());
            }
            if(applyOrderInfo.getCancelDate()!=null){
                approvalRecordVo.setOrderRefuse(applyOrderInfo.getCancelDate());
            }
            if(applyOrderInfo.getIntoFirstDate()!=null){
                approvalRecordVo.setOrderCommit(applyOrderInfo.getIntoFirstDate());
            }
            if(applyOrderInfo.getCreateTime()!=null){
                approvalRecordVo.setOrderCreate(applyOrderInfo.getCreateTime());
            }
        }
        return IResponse.success(approvalRecordVo);
    }


    /**
     * 搜索资产变更
     *
     * @param condition
     * @return
     */
    @ApiOperation("搜索资产变更")
    @PostMapping("/searchForAssertChange")
    public IResponse searchForAssertChange(@RequestBody QueryCondition<OrderOprCondition> condition) {
        List<ApplyOprRecord> list=applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda().eq(ApplyOprRecord::getApplyNo,condition.getCondition().getApplyNo()));
        return IResponse.success(list);
    }

    /**
     * 审批记录查询
     * */
    @PostMapping(value = "/getApprovalRecordNew")
    @ApiOperation("获取审批记录")
    public IResponse getApprovalRecordNew(@RequestParam("applyNo") String applyNo){
        ApprovalRecordVo approvalRecordVo=new ApprovalRecordVo();
        approvalRecordVo.setApplyNo(applyNo);
        ApplyCarDetails applyCarDetails=applyCarDetailsService.getCarDetailsByApplyNo(applyNo);
        if(applyCarDetails!=null){
            approvalRecordVo.setBrandName(applyCarDetails.getBrandName());
            approvalRecordVo.setModelName(applyCarDetails.getModelName());
            approvalRecordVo.setStyleName(applyCarDetails.getStyleName());
        }
        BigDecimal money=BigDecimal.ZERO;
        List<FinCostDetails> costDetailsList=applyCostDetailsService.getCostDetailsList(applyNo);
        if(costDetailsList.size()>0){
            approvalRecordVo.setLoanTerm(costDetailsList.get(0).getLoanTerm());
            for(FinCostDetails costDetails:costDetailsList){
                money=money.add(costDetails.getLoanAmt()==null?BigDecimal.ZERO:costDetails.getLoanAmt());
            }
            approvalRecordVo.setLoanAmt(money);
        }
        List<ApproveRecordNodeVo> voList =new ArrayList<>();
        ApplyOrderInfo applyOrderInfo=applyOrderInfoService.getOrderInfoByApplyNo(applyNo);
        ApplyContractInfo applyContractInfo=applyContractInfoService.getContractInfoByAppplyNo(applyNo);
        if(applyOrderInfo!=null){
            approvalRecordVo.setCustName(applyOrderInfo.getCustName());
            approvalRecordVo.setProductName(applyOrderInfo.getProductName());
            //订单创建时间
            if(applyOrderInfo.getCreateTime()!=null){
                ApproveRecordNodeVo startVo= new ApproveRecordNodeVo();
                startVo.setApproveNode(ApproveRecordEnum.NODE_ORDER_CREATE.getName());
                startVo.setApproveDate(applyOrderInfo.getCreateTime());
                voList.add(startVo);
            }
            //订单提交时间
            if(applyOrderInfo.getIntoFirstDate()!=null){
                ApproveRecordNodeVo approvalVo= new ApproveRecordNodeVo();
                approvalVo.setApproveNode(ApproveRecordEnum.NODE_ORDER_SUBMIT.getName());
                approvalVo.setApproveDate(applyOrderInfo.getIntoFirstDate());
                voList.add(approvalVo);
            }
            //订单核准
            if(applyOrderInfo.getRiskPassDate()!=null){
                ApproveRecordNodeVo risktVo= new ApproveRecordNodeVo();
                risktVo.setApproveNode(ApproveRecordEnum.NODE_ORDER_CHECK.getName());
                risktVo.setApproveDate(applyOrderInfo.getRiskPassDate());
                voList.add(risktVo);
            }
            if(applyOrderInfo.getCancelDate()!=null){
                //进件订单拒绝
                ApproveRecordNodeVo orderCancelVo= new ApproveRecordNodeVo();
                orderCancelVo.setApproveNode(ApproveRecordEnum.NODE_ORDER_REFUSE.getName());
                orderCancelVo.setApproveDate(applyOrderInfo.getCancelDate());
                voList.add(orderCancelVo);
            }
        }
        if(applyContractInfo!=null){
            if(applyContractInfo.getLendingFirstDate()!=null){
                //放款提交时间
                ApproveRecordNodeVo loanSubmitVo= new ApproveRecordNodeVo();
                loanSubmitVo.setApproveNode(ApproveRecordEnum.NODE_LOAN_SUBMIT.getName());
                loanSubmitVo.setApproveDate(applyContractInfo.getLendingFirstDate());
                voList.add(loanSubmitVo);
            }
            if(applyContractInfo.getLendingPassDate()!=null){
                //放款通过时间
                ApproveRecordNodeVo contractVo= new ApproveRecordNodeVo();
                contractVo.setApproveNode(ApproveRecordEnum.NODE_LOAN_APPROVE.getName());
                contractVo.setApproveDate(applyContractInfo.getLendingPassDate());
                voList.add(contractVo);
            }
            if(applyContractInfo.getCancelDate()!=null){
                //放款取消
                ApproveRecordNodeVo cancelVo= new ApproveRecordNodeVo();
                cancelVo.setApproveNode(ApproveRecordEnum.NODE_LOAN_CANCEL.getName());
                cancelVo.setApproveDate(applyContractInfo.getCancelDate());
                voList.add(cancelVo);
            }
            if(applyContractInfo.getStartDate()!=null){
                //合同激活
                ApproveRecordNodeVo activatioVo= new ApproveRecordNodeVo();
                activatioVo.setApproveNode(ApproveRecordEnum.NODE_ACTIVATION.getName());
                activatioVo.setApproveDate(applyContractInfo.getStartDate());
                voList.add(activatioVo);
            }
        }
        approvalRecordVo.setVoList(voList);
        return IResponse.success(approvalRecordVo);
    }

}
